# Set output encoding to UTF-8 to ensure Unicode characters are supported
$OutputEncoding = [System.Text.Encoding]::UTF8

# Network adapter names
$adapter1 = "Realtek PCIe GbE Family Controller"  # Ethernet adapter name
$adapter1Name = "net1"
$adapter2 = "Realtek PCIe GBE Family Controller"  # Wireless adapter name
$adapter2Name = "net2"
# Speed threshold in kb/s
$thresholdSpeed = 100
# Speed check interval in seconds
$speedCheckDuration = 10
# Adapter switch timeout in seconds
$switchTimeout = 200

# Function to disable adapter
function Disable-Adapter {
    param([string]$name)
    try {
        Disable-NetAdapter -Name $name -ErrorAction Stop
        Write-Host "Adapter ${name} disabled successfully."
    } catch {
        Write-Host "Failed to disable adapter ${name}: $_"
    }
}

# Function to enable adapter
function Enable-Adapter {
    param([string]$name)
    try {
        Enable-NetAdapter -Name $name -ErrorAction Stop
        Write-Host "Adapter ${name} enabled successfully."
    } catch {
        Write-Host "Failed to enable adapter ${name}: $_"
    }
}

# Function to get current adapter name
function Get-CurrentAdapterName {
    param([string]$description)
    try {
        $currentAdapter = Get-NetAdapter | Where-Object { $_.InterfaceDescription -eq $description } | Select-Object -ExpandProperty Name
        Write-Host "Current adapter description matched: ${description}, Name: ${currentAdapter}"
    } catch {
        Write-Host "Failed to get current adapter name: $_"
        $currentAdapter = $null
    }
    return $currentAdapter
}

# Function to get current adapter speed (both received and sent)
function Get-CurrentAdapterSpeed {
    param([string]$name)
    try {
        # Get received and sent bytes at two time points
        $startTime = Get-Date
        $startStats = Get-NetAdapterStatistics -Name $name -ErrorAction Stop
        Start-Sleep -Seconds $speedCheckDuration
        $endStats = Get-NetAdapterStatistics -Name $name -ErrorAction Stop
        $endTime = Get-Date

        # Calculate received and sent speed
        $receivedBytes = $endStats.ReceivedBytes - $startStats.ReceivedBytes
        $sentBytes = $endStats.SentBytes - $startStats.SentBytes
        $elapsedTime = ($endTime - $startTime).TotalSeconds

        $receivedSpeed = [math]::Round($receivedBytes / $elapsedTime / 1024, 2)  # in kb/s
        $sentSpeed = [math]::Round($sentBytes / $elapsedTime / 1024, 2)  # in kb/s

        Write-Host "Received bytes: $receivedBytes, Sent bytes: $sentBytes, Elapsed time: $elapsedTime, Received speed: $receivedSpeed kb/s, Sent speed: $sentSpeed kb/s"
    } catch {
        Write-Host "Failed to get speed for adapter ${name}: $_"
        $receivedSpeed = 0
        $sentSpeed = 0
    }
    return @{ "ReceivedSpeed" = $receivedSpeed; "SentSpeed" = $sentSpeed }
}

# Initialize variables
$currentAdapter = $adapter2
$switchCount = 0

# Ensure initial state: Adapter1 disabled, Adapter2 enabled
Disable-Adapter -Name $adapter1Name
Enable-Adapter -Name $adapter2Name

# Start monitoring and switching
while ($true) {
    try {
        Write-Host "Checking current adapter and speed..."
        # Get the name of the current adapter in use
        $currentAdapterName = Get-CurrentAdapterName -description $currentAdapter
        if (-not $currentAdapterName) {
            Write-Host "Failed to get current adapter name. Exiting loop."
            break
        } else {
            Write-Host "Current adapter in use: $currentAdapterName"

            # Get the current speed of the adapter
            $speeds = Get-CurrentAdapterSpeed -name $currentAdapterName
            $receivedSpeed = $speeds.ReceivedSpeed
            $sentSpeed = $speeds.SentSpeed
            Write-Host "Current received speed: $receivedSpeed kb/s, Current sent speed: $sentSpeed kb/s"

            # Check if we need to switch adapters
            if ($receivedSpeed -lt $thresholdSpeed -and $sentSpeed -lt $thresholdSpeed) {
                # Speed is below threshold, increment switch count
                $switchCount++
                Write-Host "Speed below threshold. Switch count: $switchCount"
                if ($switchCount * $speedCheckDuration -ge $switchTimeout) {
                    # Switch timeout exceeded, switch adapter
                    Write-Host "Switch timeout exceeded. Switching adapters."
                    if ($currentAdapter -eq $adapter1) {
                        Disable-Adapter -Name $adapter1Name
                        Enable-Adapter -Name $adapter2Name
                        $currentAdapter = $adapter2
                    } else {
                        Disable-Adapter -Name $adapter2Name
                        Enable-Adapter -Name $adapter1Name
                        $currentAdapter = $adapter1
                    }
                    # Reset switch count
                    $switchCount = 0
                }
            } else {
                # Speed is above threshold, reset switch count
                Write-Host "Speed above threshold. Resetting switch count."
                $switchCount = 0
            }
        }
    } catch {
        Write-Host "Error occurred: $_"
    }

    # Wait for a specified duration before checking again
    Start-Sleep -Seconds $speedCheckDuration
}
